package com.yb.mybatis.multi.datasource.interceptor;

import com.yb.mybatis.multi.datasource.interfaces.ICurrentDataSource;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.plugin.*;

import java.sql.Connection;
import java.util.Properties;

/**
 * @author: yb
 * @date: 2021/12/30 0030 21:27
 */
@Intercepts({
        @Signature(type= StatementHandler.class,method = "prepare",args={Connection.class, Integer.class})
})
public class MybatisMultiDatasourceInterceptor implements Interceptor {

    private ICurrentDataSource currentDataSource;

    public MybatisMultiDatasourceInterceptor(ICurrentDataSource currentDataSource){
        this.currentDataSource = currentDataSource;
    }

    public MybatisMultiDatasourceInterceptor(){}

    public void setCurrentDataSource(ICurrentDataSource currentDataSource) {
        this.currentDataSource = currentDataSource;
    }

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        if(currentDataSource == null){
            throw new RuntimeException("ICurrentDataSource接口没有实现类");
        }
        final String targetDataBase = currentDataSource.getTargetDataBase();
        Connection connection = (Connection)invocation.getArgs()[0];
        connection.setCatalog(targetDataBase);
        return invocation.proceed();
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {

    }
}
